import javax.servlet.http.*;

def savePerson() {
    def e 
    
    if (model.id) {
        e = pm.load(model.id)
    } else {
    	e = pm.newEntity()
    }
    
    e.firstName = model.firstName
    e.lastName = model.lastName
    
    pm.save(e)
}

pm = new DAO("Person")
model = [:]

def person = pm.newEntity()
def message = ""
def action = request.getParameter('action')
def list 

request.parameterNames.each { name ->
	model[name] = request.getParameter(name)
}

if (model.id && model.id != "0") {
	model.id = model.id.toLong()
} else {
	model.id = null
}
		
if (action == "save") {
    message = "saving"
    savePerson()
    
} else if (action == "delete") {
    message = "deleted"
    pm.delete(model.id)
    
} else if (action == "new") { 
    message = "creating new"
    person = pm.newEntity()

} else if (action == "findByFirstName") {
	message = "finding by first name = '${model.firstName}'"
	list = pm.findByFirstName(model.firstName)

} else if (action == "findByLastName") {
	message = "finding by first name = '${model.lastName}'"
	list = pm.findByLastName(model.lastName)
	
} else if (model.id) {
    message = "loaded #${model.id}"
    person = pm.load(model.id)
}

if (!list) {
	list = pm.listAll();
}

html.html {
    head {
        title "Hello"
    }
    body {
     
        form {
            input(type:"hidden", name:"id", value:person.id)
            table {
                tr {
                    td "message"
                    td message
                }
                tr {
                    td "first name"
                    td {
                        input(type:"text", name:"firstName", value:person.firstName)
                    }
                }
                tr {
                    td "last name" 
                    td {
                        input(type:"text", name:"lastName", value:person.lastName)
                    }
                }
                tr {
                    td(colspan:2) {
                        input(type:"submit", name:"action", value:"save")
                        input(type:"submit", name:"action", value:"new")
                        input(type:"submit", name:"action", value:"findByFirstName")
                        input(type:"submit", name:"action", value:"findByLastName")
                    }
                }
            }
        }
        h2 "Items: ${list.size}"
        list.each { ee ->
            div {
                span "#${ee.id} ${ee.firstName} ${ee.lastName}"
                
                a(href:"${request.servletPath}?id=${ee.key.id}") {
                    span "edit"                                
                }
                
                a(href:"${request.servletPath}?action=delete&id=${ee.key.id}") {
                    span "delete"                                
                }
            }
        }
    }
}